<template>
  <ion-page>
    <ion-header :translucent="true">
      <ion-toolbar>
        <ion-title>我的</ion-title>
        <ion-buttons slot="end">
          <ion-button @click="logout" fill="clear">
            <ion-icon :icon="logOutOutline"></ion-icon>
            退出
          </ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>

    <ion-content :fullscreen="true">
      <ion-header collapse="condense">
        <ion-toolbar>
          <ion-title size="large">我的</ion-title>
        </ion-toolbar>
      </ion-header>

      <!-- 用户信息卡片 -->
      <ion-card class="user-card">
        <ion-card-content>
          <div class="user-info">
            <ion-avatar>
              <ion-icon :icon="personCircleOutline" size="large"></ion-icon>
            </ion-avatar>
            <div class="user-details">
              <h2>{{ userStore.user?.name }}</h2>
              <p>@{{ userStore.user?.username }}</p>
              <ion-chip :color="getRoleColor()" v-if="userStore.currentRole">
                <ion-icon :icon="getRoleIcon()"></ion-icon>
                <ion-label>{{ getRoleName() }}</ion-label>
              </ion-chip>
            </div>
          </div>
        </ion-card-content>
      </ion-card>

      <!-- 签到功能区域 -->
      <ion-card class="checkin-card" @click="goToActivity">
        <ion-card-content>
          <div class="checkin-content">
            <div class="checkin-info">
              <div class="checkin-icon">
                <ion-icon :icon="calendarOutline" size="large" color="primary"></ion-icon>
              </div>
              <div class="checkin-text">
                <h3>每日签到</h3>
                <p>签到获取活跃度，查看排行榜</p>
              </div>
            </div>
            <div class="checkin-action">
              <ion-button fill="solid" color="primary" size="small">
                <ion-icon :icon="trophyOutline" slot="start"></ion-icon>
                签到
              </ion-button>
            </div>
          </div>
        </ion-card-content>
      </ion-card>

      <!-- 消息中心 -->
      <div class="section">
        <h3 class="section-title">消息中心</h3>
        <ion-card class="message-preview-card" @click="goToMessages">
          <ion-card-content>
            <div class="message-preview">
              <div class="message-icon">
                <ion-icon :icon="mailOutline" color="primary" size="large"></ion-icon>
                <ion-badge v-if="unreadMessageCount > 0" color="danger" class="message-count-badge">
                  {{ unreadMessageCount }}
                </ion-badge>
              </div>
              <div class="message-content">
                <h4>系统消息</h4>
                <p v-if="latestMessage">{{ latestMessage.title }}</p>
                <p v-else>暂无新消息</p>
                <span class="message-time" v-if="latestMessage">{{ formatTime(latestMessage.createdAt) }}</span>
              </div>
              <ion-icon :icon="chevronForwardOutline" color="medium"></ion-icon>
            </div>
          </ion-card-content>
        </ion-card>
      </div>

      <!-- 功能菜单 -->
      <div class="section">
        <h3 class="section-title">功能菜单</h3>
        <div class="menu-list">
          <ion-item button @click="goToLandlordVerification" v-if="userStore.currentRole === 'landlord'">
            <ion-icon :icon="shieldCheckmarkOutline" slot="start" color="success"></ion-icon>
            <ion-label>房东认证</ion-label>
            <ion-icon :icon="chevronForwardOutline" slot="end" color="medium"></ion-icon>
          </ion-item>

          <ion-item button @click="goToMyProperties" v-if="userStore.currentRole === 'landlord'">
            <ion-icon :icon="homeOutline" slot="start" color="primary"></ion-icon>
            <ion-label>我的房源</ion-label>
            <ion-icon :icon="chevronForwardOutline" slot="end" color="medium"></ion-icon>
          </ion-item>

          <ion-item button @click="goToQRCode" v-if="userStore.currentRole === 'landlord'">
            <ion-icon :icon="qrCodeOutline" slot="start" color="primary"></ion-icon>
            <ion-label>机器二维码</ion-label>
            <ion-icon :icon="chevronForwardOutline" slot="end" color="medium"></ion-icon>
          </ion-item>

          <ion-item button @click="goToOrganization" v-if="userStore.currentRole === 'landlord'">
            <ion-icon :icon="businessOutline" slot="start" color="secondary"></ion-icon>
            <ion-label>我的机构</ion-label>
            <ion-icon :icon="chevronForwardOutline" slot="end" color="medium"></ion-icon>
          </ion-item>

          <ion-item button @click="goToServiceAgreement">
            <ion-icon :icon="documentTextOutline" slot="start" color="tertiary"></ion-icon>
            <ion-label>服务协议</ion-label>
            <ion-icon :icon="chevronForwardOutline" slot="end" color="medium"></ion-icon>
          </ion-item>

          <ion-item button @click="showSettings">
            <ion-icon :icon="settingsOutline" slot="start" color="medium"></ion-icon>
            <ion-label>设置</ion-label>
            <ion-icon :icon="chevronForwardOutline" slot="end" color="medium"></ion-icon>
          </ion-item>
        </div>
      </div>

      <!-- 模拟消息列表 -->
      <div class="section" v-if="showMockMessages">
        <h3 class="section-title">最近消息</h3>
        <div class="mock-messages">
          <ion-card 
            v-for="message in mockMessages.slice(0, 3)" 
            :key="message.id" 
            class="mock-message-card"
            @click="openMockMessage(message)"
          >
            <ion-card-content>
              <div class="mock-message-item">
                <div class="mock-message-icon">
                  <ion-icon 
                    :icon="getMessageIcon(message.type)" 
                    :color="getMessageColor(message.type)"
                  ></ion-icon>
                </div>
                <div class="mock-message-content">
                  <h4>{{ message.title }}</h4>
                  <p>{{ message.content.substring(0, 50) }}...</p>
                  <span class="mock-message-time">{{ formatTime(message.createdAt) }}</span>
                </div>
                <ion-badge v-if="!message.isRead" color="danger" class="unread-badge">
                  未读
                </ion-badge>
              </div>
            </ion-card-content>
          </ion-card>
          
          <ion-button 
            expand="block" 
            fill="outline" 
            @click="goToMessages"
            class="view-all-btn"
          >
            查看全部消息
          </ion-button>
        </div>
      </div>
    </ion-content>
  </ion-page>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import {
  IonPage,
  IonHeader,
  IonToolbar,
  IonTitle,
  IonContent,
  IonButtons,
  IonButton,
  IonIcon,
  IonCard,
  IonCardContent,
  IonAvatar,
  IonChip,
  IonLabel,
  IonItem,
  IonBadge,
  alertController,
  toastController
} from '@ionic/vue'
import {
  personCircleOutline,
  logOutOutline,
  homeOutline,
  mailOutline,
  chevronForwardOutline,
  shieldCheckmarkOutline,
  qrCodeOutline,
  documentTextOutline,
  settingsOutline,
  informationCircleOutline,
  warningOutline,
  checkmarkCircleOutline,
  calendarOutline,
  trophyOutline,
  businessOutline
} from 'ionicons/icons'
import { useUserStore } from '@/stores/user'

// 消息类型定义
interface MockMessage {
  id: number
  type: 'verification' | 'property' | 'system' | 'warning' | 'success'
  title: string
  content: string
  createdAt: string
  isRead: boolean
}

const router = useRouter()
const userStore = useUserStore()

// 未读消息数量
const unreadMessageCount = ref(2)

// 是否显示模拟消息
const showMockMessages = ref(true)

// 模拟消息数据
const mockMessages = ref<MockMessage[]>([
  {
    id: 1,
    type: 'verification',
    title: '房东认证审核通过',
    content: '恭喜您！您的房东认证已通过审核，现在可以发布房源信息了。请确保房源信息真实有效，遵守平台规定。',
    createdAt: '2024-01-15T10:30:00Z',
    isRead: false
  },
  {
    id: 2,
    type: 'property',
    title: '房源发布成功',
    content: '您发布的房源"阳光小区三室两厅"已成功上线，租客现在可以搜索到您的房源。建议及时回复租客咨询。',
    createdAt: '2024-01-14T16:45:00Z',
    isRead: false
  },
  {
    id: 3,
    type: 'system',
    title: '五月租房返现活动',
    content: '五月租房返现活动正在进行中！成功出租房源最高可获得4000元返现，活动截止到5月31日。',
    createdAt: '2024-01-13T09:15:00Z',
    isRead: true
  }
])

// 最新消息
const latestMessage = computed(() => {
  return mockMessages.value.find(msg => !msg.isRead) || mockMessages.value[0]
})

// 获取角色名称
const getRoleName = () => {
  const roleNames: Record<string, string> = {
    admin: '管理员',
    landlord: '房东',
    tenant: '租客'
  }
  return roleNames[userStore.currentRole || ''] || userStore.currentRole
}

// 获取角色颜色
const getRoleColor = () => {
  const colors: Record<string, string> = {
    admin: 'danger',
    landlord: 'warning',
    tenant: 'primary'
  }
  return colors[userStore.currentRole || ''] || 'medium'
}

// 获取角色图标
const getRoleIcon = () => {
  const icons: Record<string, any> = {
    admin: shieldCheckmarkOutline,
    landlord: homeOutline,
    tenant: personCircleOutline
  }
  return icons[userStore.currentRole || ''] || personCircleOutline
}

// 获取消息图标
const getMessageIcon = (type: string) => {
  const icons = {
    verification: shieldCheckmarkOutline,
    property: homeOutline,
    system: informationCircleOutline,
    warning: warningOutline,
    success: checkmarkCircleOutline
  }
  return icons[type as keyof typeof icons] || informationCircleOutline
}

// 获取消息颜色
const getMessageColor = (type: string) => {
  const colors = {
    verification: 'success',
    property: 'primary',
    system: 'tertiary',
    warning: 'warning',
    success: 'success'
  }
  return colors[type as keyof typeof colors] || 'medium'
}

// 格式化时间
const formatTime = (dateString: string) => {
  const date = new Date(dateString)
  const now = new Date()
  const diffInHours = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60))
  
  if (diffInHours < 1) {
    return '刚刚'
  } else if (diffInHours < 24) {
    return `${diffInHours}小时前`
  } else if (diffInHours < 48) {
    return '昨天'
  } else {
    return date.toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric'
    })
  }
}

// 跳转到消息页面
const goToMessages = () => {
  router.push('/tabs/messages')
}

// 跳转到房东认证页面
const goToLandlordVerification = () => {
  router.push('/landlord-verification')
}

// 跳转到二维码页面
const goToQRCode = () => {
  router.push('/qrcode')
}

// 跳转到服务协议页面
const goToServiceAgreement = () => {
  router.push('/service-agreement')
}

// 跳转到活跃度页面
const goToActivity = () => {
  router.push('/activity')
}

// 跳转到我的房源页面
const goToMyProperties = () => {
  router.push('/my-properties')
}

// 跳转到机构页面
const goToOrganization = () => {
  router.push('/organization')
}

// 显示设置
const showSettings = async () => {
  const toast = await toastController.create({
    message: '设置功能开发中...',
    duration: 2000,
    color: 'primary',
    position: 'top'
  })
  await toast.present()
}

// 打开模拟消息
const openMockMessage = async (message: MockMessage) => {
  // 标记为已读
  if (!message.isRead) {
    message.isRead = true
    unreadMessageCount.value = Math.max(0, unreadMessageCount.value - 1)
  }

  // 显示消息详情
  const alert = await alertController.create({
    header: message.title,
    message: message.content,
    buttons: ['确定']
  })
  await alert.present()
}

// 退出登录
const logout = async () => {
  const alert = await alertController.create({
    header: '确认退出',
    message: '确定要退出登录吗？',
    buttons: [
      {
        text: '取消',
        role: 'cancel'
      },
      {
        text: '确定',
        handler: () => {
          userStore.logout()
          router.replace('/login')
        }
      }
    ]
  })
  await alert.present()
}
</script>

<style scoped>
.user-card {
  margin: 16px;
  margin-bottom: 0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-info ion-avatar {
  width: 60px;
  height: 60px;
}

.user-details h2 {
  margin: 0 0 4px 0;
  color: var(--ion-color-dark);
}

.user-details p {
  margin: 0 0 8px 0;
  color: var(--ion-color-medium);
  font-size: 14px;
}

.checkin-card {
  margin: 16px;
  margin-top: 8px;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.checkin-card:hover {
  transform: translateY(-2px);
}

.checkin-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.checkin-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.checkin-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: rgba(var(--ion-color-primary-rgb), 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.checkin-text h3 {
  margin: 0 0 4px 0;
  color: var(--ion-color-dark);
  font-size: 16px;
  font-weight: 600;
}

.checkin-text p {
  margin: 0;
  color: var(--ion-color-medium);
  font-size: 14px;
}

.checkin-action {
  flex-shrink: 0;
}

.section {
  margin: 20px 16px;
}

.section-title {
  margin: 0 0 12px 0;
  color: var(--ion-color-dark);
  font-weight: 600;
  font-size: 16px;
}

.message-preview-card {
  margin: 0;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.message-preview-card:hover {
  transform: translateY(-2px);
}

.message-preview {
  display: flex;
  align-items: center;
  gap: 16px;
}

.message-icon {
  position: relative;
}

.message-count-badge {
  position: absolute;
  top: -8px;
  right: -8px;
  min-width: 20px;
  height: 20px;
  font-size: 12px;
  line-height: 20px;
}

.message-content {
  flex: 1;
}

.message-content h4 {
  margin: 0 0 4px 0;
  color: var(--ion-color-dark);
  font-size: 16px;
}

.message-content p {
  margin: 0 0 4px 0;
  color: var(--ion-color-medium);
  font-size: 14px;
}

.message-time {
  font-size: 12px;
  color: var(--ion-color-medium);
}

.menu-list {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.mock-messages {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.mock-message-card {
  margin: 0;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.mock-message-card:hover {
  transform: translateY(-1px);
}

.mock-message-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.mock-message-icon {
  margin-top: 4px;
}

.mock-message-content {
  flex: 1;
}

.mock-message-content h4 {
  margin: 0 0 4px 0;
  color: var(--ion-color-dark);
  font-size: 14px;
  font-weight: 600;
}

.mock-message-content p {
  margin: 0 0 4px 0;
  color: var(--ion-color-medium);
  font-size: 13px;
  line-height: 1.4;
}

.mock-message-time {
  font-size: 11px;
  color: var(--ion-color-medium);
}

.unread-badge {
  margin-top: 4px;
  font-size: 10px;
  min-width: 36px;
  height: 18px;
  line-height: 18px;
}

.view-all-btn {
  margin-top: 8px;
}
</style>
